<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/*
  Create – adding a user account to your website
  Retrieve – getting a list of available products
  Update – changing a user’s password or the name of a product
  Delete – removing a user account or product
 */

Class Article extends CI_Model {

    public $articles_table = "articles";

    /**
     * Add new article
     * @param type $author_id
     * @param type $title
     * @param type $text 
     */
    function add($author_id, $title, $text) {
        // check params
        if (!isset($author_id) || !isset($title)) {
            throw new Exception("Article can be posted only with author_id && title");
        }

        // configure data to insert
        $data = array(
            'author_id' => $author_id,
            'title' => $title,
            'text' => $text
        );

        // insert data
        $this->db->insert($this->articles_table, $data);

        return true;
    }

    /**
     *
     * @param type $id
     * @return array (user_id, title, article)
     */
    function retrieve($id) {
        // constructing active record query
        $query = $this->db->query("SELECT * FROM 
                                    $this->articles_table 
                                    WHERE `id` = '$id'
                                    LIMIT 1");
        // check the query success
        if($query->num_rows == 0){
            return NULL;
        }
        //if($query->)
        $result = $query->result();
        return $result[0];
    }

    /**
     * Update article by id.
     * @param type $id
     * @param type $author_id
     * @param type $title
     * @param type $text
     * @return true on success
     */
    function update($id, $title, $text) {
        // configure data to update
        $data = array(
            'title' => $title,
            'text' => $text
        );

        // do selection and update data
        $this->db->where('id', $id);
        $this->db->update($this->articles_table, $data);

        return true;
    }

    /**
     * Delete article
     * @param type $id
     * @return true on success
     */
    function delete($id) {
        $this->db->where('id', $id);
        $this->db->delete($this->articles_table);

        return true;
    }

    /**
     * returns the articles 
     * @param type $limit the number of returned articles
     * @param type $offset from this number.
     * @return type 
     */
    function get_articles($limit = NULL, $offset = NULL) {
        $this->db->limit($limit, $offset);
        return $this->db->get($this->articles_table);
    }
    
    
    /**
     * Returns the number of articles
     * @return type 
     */
    function count_articles(){
        return $this->db->count_all_results($this->articles_table);
    }

}